//
//  ViewController.m
//  CAShapeLayerColorful
//
//  Created by Xwoder on 17/2/4.
//  Copyright © 2017年 Xwoder. All rights reserved.
//

#import "ViewController.h"

static CGFloat const sideLength = 300;

@interface ViewController ()

@property (nonatomic, weak) CAShapeLayer *shapeLayer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    NSMutableArray *colors = [NSMutableArray array];
    for (NSUInteger hue = 0; hue <= 360; ++hue) {
        UIColor *color = [UIColor colorWithHue:hue/360.0 saturation:1.0 brightness:1.0 alpha:1];
        [colors addObject:(id)color.CGColor];
    }
    
    CGRect rect = CGRectMake(0, 0, sideLength, sideLength);
    
    // UIBezierPath
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithOvalInRect:rect];
    
    // CAShapeLayer
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = [UIColor blackColor].CGColor;
    shapeLayer.path = bezierPath.CGPath;
    shapeLayer.lineWidth = 20;
    shapeLayer.lineCap = kCALineCapRound;
    [self.view.layer addSublayer:shapeLayer];

    // CAGradientLayer
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.bounds = rect;
    gradientLayer.position = self.view.center;
    gradientLayer.startPoint = CGPointMake(0.5, 0);
    gradientLayer.endPoint = CGPointMake(0.5, 1);
    gradientLayer.cornerRadius = sideLength / 2;
    gradientLayer.colors = colors;
    gradientLayer.mask = shapeLayer;
    [self.view.layer addSublayer:gradientLayer];
    
    self.shapeLayer = shapeLayer;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"strokeEnd";
    animation.duration = 2;
    animation.fromValue = @(0);
    animation.toValue = @(1);
    [self.shapeLayer addAnimation:animation forKey:nil];
}

@end
